package fr.norsys.mapper.jndi;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;

import junit.framework.TestCase;
import fr.norsys.mapper.core.MapperException;
import fr.norsys.mapper.manager.MapperManager;
import fr.norsys.mapper.xml.XMLConfigurator;
import fr.norsys.mapper.xml.XMLConfiguratorException;

/**
 * Integration testing class for XML configuration and 
 * execution of a search query.
 * <p>
 * This class executes  a simple scenario of querying the 
 * telephone, mail and full name of a user based
 * on its name and surname. The query is executed 
 * on a true LDAP server.
 * </p>
 * <p>
 * This class uses MockLdap as backend.
 * </p>
 * @author nono
 *
 */
public class NetXMLJNDISearchTest extends TestCase {

	
	private XMLConfigurator xc;
	private MapperManager mgr;

	protected void setUp() throws Exception {
		super.setUp();
		this.xc = new XMLConfigurator();
		this.mgr = new MapperManager();
		
	}

	/**
	 * Test raw LDAP query
	 * @throws NamingException 
	 *
	 */
	public void test00LDAP() throws NamingException {
		Hashtable ht = new Hashtable();
		ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
		ht.put(Context.PROVIDER_URL,"ldap://130.81.0.6/o=canam");
		ht.put(Context.SECURITY_PRINCIPAL,"cn=cdmread,ou=users,o=services");
		ht.put(Context.SECURITY_CREDENTIALS,"cdmread");
		DirContext dir = new InitialDirContext(ht);
		SearchControls ctls = new SearchControls();
		ctls.setReturningAttributes(null);
		ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
		String filter = "(cn=ut050568)";
		NamingEnumeration ne = dir.search("ou=Personnes",filter,ctls);
		System.err.println(ne);
	}
	
	public void test01Base() throws MapperException, XMLConfiguratorException {
		// parse XML configuration file
		xc.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("jndi-sample-net.xml"));
		// configure manager
		this.xc.configure(this.mgr);
		this.mgr.set("user","cn=cdmread,ou=users,o=services");
		this.mgr.set("url","ldap://130.81.0.6/o=canam");
		this.mgr.set("pass","cdmread");
		this.mgr.setConfigured();
		this.mgr.start();
		// execute query 
		SearchMapper sm = (SearchMapper)this.mgr.getMapper("telAndMail");
		/* populate input */
		Map input = new HashMap();
		input.put("pid", "ut050568");
		input.put("prenom", "Sandrine");
		List ret = sm.search(input,null);
		this.mgr.release(sm);
		assertEquals(1,ret.size());
		assertEquals("RICHART Jean-danielle",((Map)ret.get(0)).get("nom"));
	}
}
